package com.atguigu.tingshu.dispatch.job;

import com.atguigu.tingshu.dispatch.mapper.XxlJobLogMapper;
import com.atguigu.tingshu.model.dispatch.XxlJobLog;
import com.atguigu.tingshu.search.client.SearchFeignClient;
import com.atguigu.tingshu.user.client.UserInfoFeignClient;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class DispatchJobHandler {

    @Autowired
    private SearchFeignClient searchFeignClient;

    @Autowired
    private XxlJobLogMapper xxlJobLogMapper;

    //  注入用户远程调用对象
    @Autowired
    private UserInfoFeignClient userInfoFeignClient;

    /**
     * 更新排行榜
     */
    @XxlJob("updateRanking")
    public void updateRanking() {
        //  创建一个对象
        XxlJobLog xxlJobLog = new XxlJobLog();
        xxlJobLog.setJobId(XxlJobHelper.getJobId());
        try {
            //  打印log日志
            log.info("start");
            long startTime = System.currentTimeMillis();
            //  调用方法;
            searchFeignClient.updateLatelyAlbumRanking();
            long endTime = System.currentTimeMillis();
            xxlJobLog.setTimes((int) (endTime - startTime));
            xxlJobLog.setStatus(1);
        } catch (Exception e) {
            xxlJobLog.setStatus(0);
            xxlJobLog.setError(e.getMessage());
        }
        //  保存到数据库中;
        xxlJobLogMapper.insert(xxlJobLog);
        //  打印日志结束;
        log.info("end");
    }

    /**
     * 更新用户会员状态
     */
    @XxlJob("updateUserVipStatus")
    public void updateUserVipStatus() {
        //  创建一个对象
        XxlJobLog xxlJobLog = new XxlJobLog();
        xxlJobLog.setJobId(XxlJobHelper.getJobId());
        try {
            //  打印log日志
            log.info("start");
            long startTime = System.currentTimeMillis();
            //  调用方法;
            userInfoFeignClient.updateUserVipStatus();
            long endTime = System.currentTimeMillis();
            xxlJobLog.setTimes((int) (endTime - startTime));
            xxlJobLog.setStatus(1);
        } catch (Exception e) {
            xxlJobLog.setStatus(0);
            xxlJobLog.setError(e.getMessage());
        }
        //  保存到数据库中;
        xxlJobLogMapper.insert(xxlJobLog);
        //  打印日志结束;
        log.info("end");
    }
}